<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* div {
            position: absolute;
            width: 300px;
            height: 200px;
            background-color: pink;
        } */

        span {
            display: block;
            position: absolute;
            top: 100px;
            width: 100px;
            height: 200px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <!-- <div>动画原理</div> -->
    <span>span</span>
    <button class="btn500">点击span500</button>
    <button class="btn800">点击span800</button>

    <script>
        // 算法：步长值 = (目标值-现在的位置 ) / 10
        var span = document.querySelector('span')
        var btn500 = document.querySelector('.btn500')
        var btn800 = document.querySelector('.btn800')
        function animte(obj, target,callback) {
            // 避免重复点击事件 导致定时器加速 每执行定时器时先清除上一个定时器
            clearInterval(obj.timer)
            obj.timer = setInterval(function () {
                // 步长值写在定时器里面
                var step = (target - obj.offsetLeft) / 10;
                // 获得的步长值为正数则往上取整 负数往下取整
                step = step >= 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer)
                    if(callback) {
                        callback()
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px'
            }, 15)
        }
        btn500.addEventListener('click', function () {
            animte(span, 500)
        })
        btn800.addEventListener('click', function () {
            // 声明函数可以当做实参传递给形参
            animte(span, 800,function(){
               span.style.backgroundColor = 'red'

            })
        })
    </script>
</body>

</html>